const express = require('express');

const util = require('../util');
const db = require('../db_helper');

const router = express.Router();
const logger = util.logger;

/**
 * 替换原有的 get|post 函数，由于原函数没有异常捕获，会出现
 */
function change (router, name){
  if (typeof(router[name]) === 'function'){
    router['__' + name] = router[name];
    router[name] = (url, fun) =>{
      router['__' + name](url, async (req, res, next)=>{
        try{
          let json = await fun(req.body);
          res.json({
            head: util.sucResMsg,
            body: json
          });    //如果执行过写入响应操作，在此处可以结束，如果已经写入，此处再次写入将无效
        }catch(e){
          logger.error('error------>' ,e);
          res.json({
            head: util.getErrMsg('-99'),
            message: e.message,
            stack: e.stack
          });
          next();
        }
      });
    }
  }
}

change(router, 'get');
change(router, 'post');

router.post('/alysisList', async (body)=>{
  let conn = db.getConn();
  logger.debug('body:', body);
  let data = await conn.table('alysis')
    .where({type: 'articleD', aid: 7})
    .order('date desc')
    .page(body.page, body.num)
    .countSelect();
  util.parseJson(data.data);
  return data;
});

router.post('/alysis7days', async (body) =>{
  let conn = db.getConn();
  logger.debug('选择日期:' + body.date);
  let end = body.date;
  let begin = new Date(end);
  begin.setDate(begin.getDate() - 6);
  begin = begin.format('yyyy-MM-dd');
  let data = await conn.table('alysis')
    .where({
      type: 'articleD',
      aid: 7,
      date: ['between', `${begin},${end}`]
    })
    .order('date desc')
    .select();
  util.parseJson(data);
  return {
    alysis: data
  };
});


module.exports = router;
